<?php
namespace app\api\controller;

use app\api\service\SaleService;
use app\common\model\tang\RepairMarrerConfig;
use app\common\model\tang\Merchant;
use app\common\model\tang\RepairMarrer as marrerModel;
use app\common\model\tang\SaleReportLog;
use app\common\model\tang\SendConfig;

use think\facade\Db;
use app\common\model\tang\SaleReport;
use app\common\model\tang\SaleReportStatistical;

class RepairMarrer extends Base {

    public function getInfo()
    {
        $RepairType = (new RepairMarrerConfig())->field('id,title')->order('id desc')->select();
        $data['typeList'] = $RepairType;
        $data['mobile'] = $this->getMobile();
        $merchant = (new Merchant)->field('id,name,username')->find($this->merchant_id);
        $merchantList = (new Merchant())->field('id,name,berth_number')->where('status',1)->where('mobile', $this->mobile)->select()->toArray();
        if(empty($merchantList)){ //说明是员工
            $merchantList = (new Merchant())->field('id,name')->where('status', 1)->where('id', $this->merchant_id)->select();
        }
        if (!empty($merchant)) {
            $data['name'] = $merchant['username'];
            $data['merchant_name'] = $merchant['name'];
            $data['merchant_id'] = $merchant['id'];
        }
        $data['merchantList'] = $merchantList;
        return SendSuccess('success', $data);
    }
    /**
     * 提交报事
     */
    public function addRecord()
    {
        $param = $this->request->param();
        if(empty($param['merchant_id'])){
            return  SendError('参数错误');
        }
        $param['start_time'] = strtotime($param['start_time']);
        $param['end_time'] = strtotime($param['end_time']);
        $param['mobile'] = $this->mobile;
        Db::startTrans();
        try {
            $record = new marrerModel();
            $recordInfo = $record->where($param)->whereTime('create_time','today')->find();
            if (!empty($recordInfo)) {
                return SendError('请勿重复提交');
            }
            $param['create_time'] = time();
            $param['order_sn'] = MarrerSn();
            $result = $record->insertGetId($param);
            if ($result) {
                Db::commit();
                return SendSuccess('报事成功', '');
            } else {
                return SendError('系统繁忙');
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
        }
    }
    public function addRecordNew()
    {
        $param = $this->request->param();
        if(empty($param['merchant_id'])){
            return  SendError('参数错误');
        }
        $param['start_time'] = strtotime($param['start_time']);
        $param['end_time'] = strtotime($param['end_time']);
        $param['mobile'] = $this->mobile;
        Db::startTrans();
        try {
            $record = new marrerModel();
            $recordInfo = $record->where($param)->whereTime('create_time','today')->find();
            if (!empty($recordInfo)) {
                return SendError('请勿重复提交');
            }
            $param['create_time'] = time();
            $param['order_sn'] = MarrerSn();
            $result = $record->insertGetId($param);
            if ($result) {
                Db::commit();
                return SendSuccess('报事成功', '');
            } else {
                return SendError('系统繁忙');
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
        }
    }
    //获取报事列表
    public function marrerList(){
        $marrer = new marrerModel();
        $result = $marrer->with(['merchant','repair'])->order('id desc')->select();
        if(!$result->isEmpty()){
            $result = $result->toArray();
            foreach ($result as $key=>$val){
                if(!empty($val['create_time'])){
                    $result[$key]['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
                }
                if(!empty($val['start_time'])){
                    $result[$key]['start_time'] = date('Y-m-d',$val['start_time']);
                }
                if(!empty($val['end_time'])){
                    $result[$key]['end_time'] = date('Y-m-d',$val['end_time']);
                }
                $result[$key]['images'] = explode(',',$val['images']);
                $result[$key]['type'] = $val['title'];
            }
        }
        return SendSuccess('success', $result);
    }
    /**
     * 获取报事详情
     */
    public function marrerDetail(){
        $id = $this->request->param('id/d');
        if(empty($id)){
            return SendError('请传入id');
        }
        $sale = new marrerModel();
        $result = $sale->with(['merchant','repair'])->find($id);
        if(empty($result)){
            return  SendError('报事详情不存在');
        }
        $result = $result->toArray();

        if(!empty($result['create_time'])){
            $result['create_time'] = date('Y-m-d H:i:s',$result['create_time']);
        }
        if(!empty($result['start_time'])){
            $result['start_time'] = date('Y-m-d',$result['start_time']);
        }
        if(!empty($result['end_time'])){
            $result['end_time'] = date('Y-m-d',$result['end_time']);
        }
        $result['images'] = explode(',',$result['images']);
        return  SendSuccess('success',$result);
    }
    /**
     * 销售上报
     */
    public function saleReportNew(){
        $param = $this->request->param();
//        $param = [
//            'money'=>18.12,
//            'sale_number'=>5,
//            'images'=>'122222222222222',
//            'merchant_id'=>'333',
//            'report_time'=>'2022-02-17'
//        ];
        if(empty($param['merchant_id'])){
            return SendError('请选择要上报的铺位');
        }
        $merchant_id = $param['merchant_id'];
        $param['money'] = $param['money']*100;
        $param['report_time'] = strtotime($param['report_time']);
        $merchantInfo = (new Merchant())->where('id',$merchant_id)->find();
        $saleConfig = (new SendConfig())->find(1);
        Db::startTrans();
        try {
            $sale = new SaleReport();
            $recordInfo = $sale->whereIn('status',[0,1])->where('merchant_id',$merchant_id)->where('report_time',$param['report_time'])->find();
            if (!empty($recordInfo)) {
                return SendError('您已上报过'.date('Y-m-d',$param['report_time']));
            }
            $param['create_time'] = time();
            $param['status'] = $saleConfig['is_apply'];
            $param['is_auto'] = $saleConfig['is_apply'];
            $result = $sale->save($param);
            if(!empty($merchantInfo['UniqueKey'])){
                $thirdSysShopUniqueKey=$merchantInfo['UniqueKey'];
                $data = [
                    [
                        'thirdSysShopUniqueKey'=>$thirdSysShopUniqueKey,
                        'shopUploadDatas'=>[
                            [
                                'tradeDate'=>date('Y-m-d',$param['report_time']),
                                'uploadAmount'=>$param['money']/100,
                                'uploadCount'=>$param['sale_number']
                            ]
                        ]
                    ]
                ];
                $saleService = new SaleService();
                $saleResult = $saleService->requestPost($data);
                $saleLog = new SaleReportLog();
                $saleLogData['merchant_id'] = $merchantInfo['id'];
                $saleLogData['code'] = $merchantInfo['code'];
                $saleLogData['requestInfo'] = json_encode($data);
                $saleLogData['returnInfo'] = json_encode($saleResult);
                $saleLogData['create_time'] = time();
                $saleLogId = $saleLog->insertGetId($saleLogData);
                if(isset($saleResult['retCode'])&&$saleResult['retCode']!=0){
                    $saleLog->update(['status'=>2],['id'=>$saleLogId]);
                    return SendError($saleResult['retMsg']);
                }
            }
            if($result){
                Db::commit();
                return SendSuccess('销售上报成功', '');
            }else{
                return SendError('系统繁忙,请稍后重试');
            }

        }catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
        }
    }
    /**
     * 获取已上报列表
     */
    public function saleList(){
        $sale = new SaleReport();
        $result = $sale->with(['merchant'])->where('merchant_id',$this->merchant_id)->order('report_time desc')->select();
        if(!$result->isEmpty()){
            $result = $result->toArray();
            foreach ($result as $key=>$val){
                if(!empty($val['create_time'])){
                    $result[$key]['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
                }
                if(!empty($val['report_time'])){
                    $result[$key]['report_time'] = date('Y-m-d',$val['report_time']);
                }
                $result[$key]['images'] = explode(',',$val['images']);
                $result[$key]['money'] = $val['money']/100;
            }
        }
        return SendSuccess('success', $result);
    }
    /**
     * 查看销售上报详情
     */
    public function saleDetail(){
        $id = $this->request->param('id/d');
        if(empty($id)){
            return SendError('请传入id');
        }
        $sale = new SaleReport();
        $result = $sale->with(['merchant'])->find($id);
        if(empty($result)){
            return  SendError('上报详情不存在');
        }
        $result = $result->toArray();
        $result['money'] = $result['money']/100;
        $result['create_time'] = date('Y-m-d H:i:s',$result['create_time']);
        $result['report_time'] = date('Y-m-d',$result['report_time']);
        $result['images'] = explode(',',$result['images']);
        return  SendSuccess('success',$result);
    }
    /**
     * 获取未上报日期或者审核未通过
     */
    public function getNoReport(){
        $merchant_id = $this->merchant_id;
        $sale = new SaleReport();
        $date_from = $sale->where('merchant_id',$merchant_id)->order('report_time asc')->value('report_time');
        $reportList = $sale->where('merchant_id',$merchant_id)->order('report_time asc')->whereIn('status',[0,1])->column('report_time');
        $date_to = strtotime(date('Y-m-d',time()));
        $date = [];
        if(!empty($date_from)){
            for ($i=$date_from; $i<=$date_to; $i+=86400)
            {
                array_push($date,date('Y-m-d',$i));
            }
            $isReport = $sale->where(['merchant_id'=>$merchant_id])->whereTime('report_time','yesterday')->where('status','<',2)->find();
            if(empty($isReport)){
                $res['isReport'] = 0;
            }else{
                $res['isReport'] = 1;
            }
            //找出审核拒绝的
        $refuse = $sale->whereBetweenTime('report_time',$date_from,$date_to)->where('status',2)->where('merchant_id',$merchant_id)->column('report_time');
//        $noArefuse = [];
            //找出未上报的日期
            foreach ($date as $k=>$v){
                foreach ($reportList as $ks=>$vs){
                    if($v==date('Y-m-d',$vs)){
                        unset($date[$k]);
                    }
                }
            }
        if(!empty($refuse)){
            foreach($date as $ks=>$vs){
                foreach ($refuse as $kk=>$vv){
                    if($vs==date('Y-m-d',$vv)){
                        $date[$ks] = date('Y-m-d',$vv);
                    }
                }
            }
        }
        }

        $res['noArefuse'] = $date;
        return SendSuccess('success',$res);
    }
    public function getReport(){ //
        $merchant = (new Merchant())->where('status',30)->whereNotNull('identification')->column('id');
        $report = (new SaleReport())->whereTime('report_time','yesterday')->where('status','<>',2)->column('merchant_id');
        foreach ($report as $k=>$v){
            foreach ($merchant as $ks=>$vs){
                if($v==$vs){
                    unset($merchant[$ks]);
                }
            }
        }
        $info['report_time'] = date('Y-m-d',strtotime('-1 day'));
        $info['report'] = count($report);
        $info['no_report'] = count($merchant);
        $info['merchant_list'] = implode(',',$merchant);
        (new SaleReportStatistical())->save($info);
    }
}